import React, { Component } from 'react'
import { Modal, message, List } from 'antd'
import { getContext } from '@/context/common/applicationContext'
import { post } from '@/utils/requestUtil'

/**
 * 消息提示组件
 * 每次提示5条系统消息
 * @author liu_jshan
 * @version 1.0 20240502
 */
class MessagePrompt extends Component {

    constructor(props) {
        super(props)
        this.state = {
            display: false, //是否需要展示
            unreadMessageContent: [],
            unreadMessageId: []
        }
    }

    async componentDidMount() {
        const {unreadMessage} = this.props.userMessage
        let unreadMessageContent = []
        let unreadMessageId = []
        for (let i = 0; i < unreadMessage.length && i < 5; i++) {
            if (unreadMessage[i].messageType === 'systemMessage') {
                unreadMessageContent.push(`[${unreadMessage[i].sendTime}]: ${unreadMessage[i].messageContent}`)
                unreadMessageId.push(unreadMessage[i].id)
            }
        }
        if (unreadMessageContent && unreadMessageContent.length > 0) {
            await new Promise(resolve => {
                this.setState({
                    display: true,
                    unreadMessageContent,
                    unreadMessageId
                }, resolve)
            })
        }
    }

    onCancel = async () => {
        const response = await post('/message/read', {
            body: JSON.stringify(this.state.unreadMessageId)
        })
        if (response && response.code === 200) {
            message.success('消息已读')
            if (this.props.updateUserMessage && typeof this.props.updateUserMessage === 'function') {
                await this.props.updateUserMessage()
            }
        }
        await new Promise(resolve => {
            this.setState({
                display: false
            }, resolve)
        })
    }

    render() {
        if (!this.state.display) return ''
        return (
            <Modal
                title='未读消息'
                open={this.state.display}
                onCancel={this.onCancel}
                footer={null}
                width={800}
            >   <div style={{ maxHeight: 600, overflow: 'auto' }}>
                    <List
                        size='large'
                        dataSource={this.state.unreadMessageContent}
                        renderItem={(item) => <List.Item>{item}</List.Item>}
                    >
                    </List>
                </div>
            </Modal>
        )
    }
}

export default getContext(MessagePrompt);
